<template>
	<div>
		<el-form
      ref="updateFormRef"
      :model="updateForm"
      :rules="updateRules"
      label-width="150px"
      :inline="true"
      label-position="left"
      status-icon
      inline-message
      style="width:80%;margin-left:auto;margin-right: auto;padding:30px 20px;text-align: center;"
    >
			<el-row type="flex" justify="center">
        <el-col :span="12">
          <el-form-item label="选择角色" prop="category_id">
						<SelectRole 
							v-model:role-id-array="updateForm.roleIdArray"
							v-model:role-id-item-array="updateForm.role"
							>
						</SelectRole>
					</el-form-item>
        </el-col>
      </el-row>
			<el-row type="flex" justify="center">
        <el-col :span="12">
           <el-form-item label="手机号" prop="phone">
            <el-input v-model="updateForm.phone" placeholder="手机号" clearable/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="center" style="text-align: center;">
        <el-col :span="12" >
          <el-form-item>
            <el-button type="primary" @click="submitForm(updateFormRef)">编辑管理员角色</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12" >
          <el-form-item>
            <el-button @click="resetForm(updateFormRef)">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
	</div>
</template>
<script setup lang="ts">
//系统
import type { FormInstance, FormRules} from 'element-plus'
//公共组件
import SelectRole from '@/pages/laravel-fast-api/v1/components/element/Role/SelectRole.vue'
//api和type
import type { UpdateAdmin } from '@/api/laravel-fast-api/v1/user/admin/admin-type'
import AdminAPI from '@/api/laravel-fast-api/v1/user/admin/admin-api'

//定义组件名称
defineOptions({
  name: 'UpdateAdminForm'
})

const updateFormRef = ref<FormInstance>()
const updateForm = reactive<UpdateAdmin>({
	id: 0,
	role: [],
	roleIdArray:[],
	phone:''
})

const updateRules = reactive<FormRules<UpdateAdmin>>({
		id: [
			{ type: 'number',required: true, message:'必须有值', trigger: 'blur' },
		]
})

//初始化表单
const initUpdateForm = () => {
	updateForm.id = 0
	updateForm.role = []
}

//定义props
const props = withDefaults(defineProps<{
  propsUpdateForm?: UpdateAdmin
}>(), {
  propsUpdateForm: () => ({
		id: 0,
		role: [],
		roleIdArray:[],
		phone:''
	})
})

//监听父级表单值的变化
watch(
  () => props.propsUpdateForm,
  (newVal, oldVal) => {
    //console.log('整个对象变化：', newVal, oldVal)
		Object.assign(updateForm,newVal)
		
  },
  { deep: true,immediate:true } // 因为是对象，需要开启深度监听
)

//emit
const emit = defineEmits(['update:CloseDialog'])

//提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  try {
    // 1. 表单校验（async/await 语法更简洁）
    const valid = await formEl.validate();
    // 2. 调用后端新增接口
		if(valid)
		{
			//console.log(updateForm)
			const result = await AdminAPI.updateAdmin(updateForm);
			// 3. 提交成功提示
			ElMessage.success(result.msg);
			// 4. 重置表单（可选，根据业务需求）
			resetForm(formEl);
			// 初始化表单
			initUpdateForm()
			// 6. 关闭对话框（可选，根据业务需求）
			emit('update:CloseDialog', false)
			
		}
    
  } catch (error) {
    // 5. 处理错误（校验失败或接口报错）
    const err = error as Error;
    ElMessage.error(`提交失败：${err.message || '未知错误'}`);
    //console.log('提交错误：', error);
  }
}

//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style lang="scss" scoped>

/**表单 */
 .content  :v-deep(.el-form-item__label){
   width:100px;
 }
 .path-item  {
  position: relative;
	left:-100px;
}
 .select,
.input {
  width: 300px;
}
.yh-input{
	width: 300px;
}
</style>